<template>
  <div>
    <!-- title -->
    <div style="height: 60px;background-color: var(--maxWhite)">
      <template v-if="!$common.isEmpty(currentChatFriendId)">
        <span style="line-height: 60px;margin-left: 20px;font-size: 18px">
          {{ friends[currentChatFriendId].remark }}
        </span>
      </template>
      <template v-else-if="!$common.isEmpty(currentChatGroupId)">
        <span style="line-height: 60px;margin-left: 20px;font-size: 18px">
          {{ groups[currentChatGroupId].groupName }}
        </span>
        <span style="line-height: 60px;margin-left: 20px;font-size: 12px;color: var(--greyFont)">
          当前在线人数：4
        </span>
      </template>
    </div>

    <!-- 聊天记录 -->
    <div class="msg-container">
      <template v-if="!$common.isEmpty(currentChatFriendId)">
        <div v-for="(item, index) in imMessages[currentChatFriendId]"
             :class="['msg-one', item.fromId === $store.state.currentUser.id ? 'message-right' : 'message-left']"
             :key="index">
          <!-- 头像 -->
          <div>
            <n-avatar object-fit="cover"
                      :size="40"
                      style="cursor: pointer"
                      @click="openFriendCircle(item.fromId, item.avatar)"
                      :src="imgUrl"/>
          </div>

          <!-- 文本消息 -->
          <div class="message" v-html="item.content"></div>

          <!-- 时间 -->
          <div class="msg-date" v-if="!$common.isEmpty(item.createTime)">
            {{ $common.getDateDiff(item.createTime) }}
          </div>
        </div>
      </template>

      <template v-else-if="!$common.isEmpty(currentChatGroupId)">
        <div v-for="(item, index) in groupMessages[currentChatGroupId]"
             :class="['msg-one', item.fromId === $store.state.currentUser.id ? 'message-right' : 'message-left']"
             :key="index">
          <!-- 头像 -->
          <div>
            <n-avatar object-fit="cover"
                      :size="40"
                      style="cursor: pointer"
                      @click="openFriendCircle(item.fromId, item.avatar, item.username)"
                      :src="imgUrl2"/>
          </div>

          <!-- 文本消息 -->
          <div class="message" v-html="item.content"
               :style="{'background': (item.fromId !== $store.state.currentUser.id ? $constant.tree_hole_color[item.fromId % $constant.tree_hole_color.length] : '')}">
          </div>

          <div class="msg-user">{{ item.username }}</div>

          <!-- 时间 -->
          <div class="msg-date" style="margin-left: 5px;margin-right: 5px"
               v-if="!$common.isEmpty(item.createTime)">
            {{ $common.getDateDiff(item.createTime) }}
          </div>
        </div>
      </template>
    </div>

    <!-- 输入框 -->
    <div style="height: 180px">
      <!-- 功能栏 -->
      <div style="padding: 10px 15px;display: flex;height: 25px">
        <!-- 表情 -->
        <n-popover placement="top-start"
                   display-directive="show"
                   trigger="click">
          <template #trigger>
            <div class="myEmoji">
              <svg viewBox="0 0 1024 1024" width="25" height="25">
                <path
                  d="M523.9 511.98m-419.5 0a419.5 419.5 0 1 0 839 0 419.5 419.5 0 1 0-839 0Z"
                  fill="#FFD629"></path>
                <path
                  d="M885.2 298.58c-1.6-0.6 37.1 68.4 49.5 128.9 46.4 227-99.9 448.6-326.9 495.1-37.9 7.8-75.7 10.1-112.5 7.7-63.2-4.2-123.6-22.8-177.3-53 0 0 348.9-269.7 567.2-578.7z"
                  fill="#FF9A2C" opacity=".1"></path>
                <path
                  d="M922.4 383.38c73.9 216.8-52.8 456-264 525.8-36.7 12.1-108.5 28.3-184.9 19.4 0-0.5 166.62-15.7 313.54-190.74C942.88 552.16 920.2 376.98 922.4 383.38z"
                  fill="#FF9A2C" opacity=".2"></path>
                <path
                  d="M790 184.48c-40.9-34.6-93.6-59.3-155.8-77.3-95.5-27.6-199.4-17.7-300.6 31.5-139.3 67.7-240.1 245.9-227.6 400.2 4.2 52 10.1 101.8 30 145.5 0.5 1 1.6 1.5 2.7 1.2 21.1-6.8 218.8-73.6 375.8-190.3 213.3-158.5 292.3-296.6 275.5-310.8z"
                  fill="#FCE99A" opacity=".24"></path>
                <path
                  d="M188.008782 408.574552a136 234.3 54.429 1 0 381.157036-272.589938 136 234.3 54.429 1 0-381.157036 272.589938Z"
                  fill="#F9F2D7" opacity=".2"></path>
                <path
                  d="M616.9 326.38m-52.7 0a52.7 52.7 0 1 0 105.4 0 52.7 52.7 0 1 0-105.4 0Z"
                  fill="#211715"></path>
                <path
                  d="M381.7 438.38l-77.6 125.3-15.5-8c-16-8.2-22.3-27.9-14.1-43.9l26.2-47.3-45.6-19.6c-15.7-8.1-21.9-27.4-13.8-43.1l8.2-16 132.2 52.6z"
                  fill="#211715"></path>
                <path
                  d="M603 479.68c27.4 56.5 14.1 119.5-29.7 140.8s-101.6-7.2-129-63.7l30.6-8c37.4-9.7 72.1-26.6 102.9-50l25.2-19.1z"
                  fill="#F94616"></path>
                <path
                  d="M514.5 567.38l8.8 6c3.6 2.5 8.3 2.8 12.2 0.7l26.9-14c3.4-1.8 5.7-5.1 6.3-8.9l1.5-10.5c1.4-10-9.4-17.1-18-11.9-9.1 5.5-20.9 11.8-35.4 17.7-8.8 3.6-10.1 15.5-2.3 20.9z"
                  fill="#E53600" opacity=".68"></path>
                <path
                  d="M922.4 383.38c73.9 216.8-52.8 456-264 525.8-36.7 12.1-108.5 28.3-184.9 19.4 0-0.5 122.92-45.83 275.21-216.29C910.21 531.51 920.2 376.98 922.4 383.38z"
                  fill="#FF9A2C" opacity=".19"></path>
                <path
                  d="M922.4 383.38c73.9 216.8-52.8 456-264 525.8-36.7 12.1-108.5 28.3-184.9 19.4 0-0.5 89.92-84.69 242.21-255.15C877.21 492.65 920.2 376.98 922.4 383.38z"
                  fill="#FF9A2C" opacity=".15"></path>
              </svg>
            </div>
          </template>
          <!-- 表情 -->
          <emoji @addEmoji="addEmoji" :showEmoji="true"></emoji>
        </n-popover>

        <!-- 图片 -->
        <div class="myEmoji" @click="sendPicture()">
          <svg viewBox="0 0 1024 1024" width="25" height="25">
            <path
              d="M512.649 512.632m-447.382 0a447.382 447.382 0 1 0 894.764 0 447.382 447.382 0 1 0-894.764 0Z"
              fill="#E0995E"></path>
            <path d="M736.34 428.748V316.902H288.958v447.382H736.34z"
                  fill="#231F20"></path>
            <path
              d="M736.34 260.979H288.958c-30.886 0-55.923 25.037-55.923 55.923V764.284c0 30.885 25.037 55.923 55.923 55.923H736.34c30.886 0 55.923-25.038 55.923-55.923V316.902c0-30.886-25.037-55.923-55.923-55.923z"
              fill="#231F20"></path>
            <path
              d="M288.958 764.284c-15.421 0-27.961-12.547-27.961-27.961V288.941c0-15.414 12.54-27.961 27.961-27.961H736.34c15.421 0 27.961 12.547 27.961 27.961v447.382c0 15.414-12.54 27.961-27.961 27.961H288.958z"
              fill="#77B3D4"></path>
            <path
              d="M736.34 288.941v447.383H288.958V288.941H736.34m0-55.923H288.958c-30.886 0-55.923 25.037-55.923 55.923v447.383c0 30.885 25.037 55.923 55.923 55.923H736.34c30.886 0 55.923-25.038 55.923-55.923V288.941c0-30.886-25.037-55.923-55.923-55.923z"
              fill="#FFFFFF"></path>
            <path d="M288.958 680.4H736.34v55.923H288.958z" fill="#FFFFFF"></path>
            <path
              d="M260.851 680.4h487.868v-40.837s-23.845-41.624-45.947-67.706c-16.44-19.4-40.989-24.891-62.407-1.059l-38.481 36.957-83.869-106.652c-31.234-39.718-82.344-39.718-113.578 0L260.851 680.4z"
              fill="#4F5D73"></path>
            <path
              d="M624.495 400.786m-41.942 0a41.942 41.942 0 1 0 83.884 0 41.942 41.942 0 1 0-83.884 0Z"
              fill="#F5CF87"></path>
            <path
              d="M736.34 288.941v447.383H288.958V288.941H736.34m0-55.923H288.958c-30.886 0-55.923 25.037-55.923 55.923v447.383c0 30.885 25.037 55.923 55.923 55.923H736.34c30.886 0 55.923-25.038 55.923-55.923V288.941c0-30.886-25.037-55.923-55.923-55.923z"
              fill="#FFFFFF"></path>
          </svg>
        </div>

        <!-- 表情包 -->
        <n-popover v-model:show="showPopoverImage"
                   display-directive="show"
                   placement="top-start"
                   trigger="click">
          <template #trigger>
            <div class="myEmoji" @click="showPopoverImage = !showPopoverImage">
              <svg viewBox="0 0 1024 1024" width="25" height="25">
                <path
                  d="M829.64898 849.502041H194.35102c-43.885714 0-79.412245-35.526531-79.412244-79.412245V253.910204c0-43.885714 35.526531-79.412245 79.412244-79.412245h635.29796c43.885714 0 79.412245 35.526531 79.412244 79.412245v516.179592c0 43.885714-35.526531 79.412245-79.412244 79.412245z"
                  fill="#D2F4FF"></path>
                <path
                  d="M909.061224 656.195918l-39.706122-48.065306L626.416327 365.714286c-19.330612-19.330612-50.677551-19.330612-70.008164 0L419.526531 502.073469c-2.612245 2.612245-5.22449 3.134694-6.791837 3.134694-1.567347 0-4.702041-0.522449-6.791837-3.134694L368.326531 464.979592c-19.330612-19.330612-50.677551-19.330612-70.008164 0l-143.673469 143.673469-39.706122 48.065306v113.893878c0 43.885714 35.526531 79.412245 79.412244 79.412245h635.29796c43.885714 0 79.412245-35.526531 79.412244-79.412245v-114.416327"
                  fill="#16C4AF"></path>
                <path
                  d="M273.763265 313.469388m-49.632653 0a49.632653 49.632653 0 1 0 99.265306 0 49.632653 49.632653 0 1 0-99.265306 0Z"
                  fill="#E5404F"></path>
                <path
                  d="M644.179592 768h-365.714286c-11.493878 0-20.897959-9.404082-20.897959-20.897959s9.404082-20.897959 20.897959-20.897959h365.714286c11.493878 0 20.897959 9.404082 20.897959 20.897959s-9.404082 20.897959-20.897959 20.897959zM461.322449 670.82449h-182.857143c-11.493878 0-20.897959-9.404082-20.897959-20.897959s9.404082-20.897959 20.897959-20.89796h182.857143c11.493878 0 20.897959 9.404082 20.897959 20.89796s-9.404082 20.897959-20.897959 20.897959z"
                  fill="#0B9682"></path>
              </svg>
            </div>
          </template>

          <div id="image-scroll-container" class="image-list">
            <n-image
              v-for="(item, index) in imageList"
              :src="item"
              @click="sendImage(item)"
              :key="index"
              width="70"
              height="70"
              lazy
              preview-disabled
              :intersection-observer-options="{root: '#image-scroll-container'}">
            </n-image>
          </div>
        </n-popover>
      </div>

      <!-- 输入框 -->
      <textarea @keydown="send($event)"
                v-model="msg"
                maxlength="1000"
                spellcheck="false"
                class="message-content">
            </textarea>
      <!-- 发送 -->
      <div class="message-send">
        <span style="color: var(--greyFont);margin-right: 15px;font-size: 12px">Ctrl+Enter：换行 | Enter：发送</span>
        <n-button @click="doSend()" type="info">
          发送
        </n-button>
      </div>
    </div>

    <!-- 聊天图片弹出框 -->
    <n-modal v-model:show="showPictureDialog">
      <div style="padding: 40px;background: var(--white);border-radius: 5px;width: 20%">
        <div style="margin: 0 0 25px;text-align: center;font-size: 18px">上传图片</div>
        <uploadPicture :prefix="picturePrefix" @addPicture="addPicture" :maxSize="5"
                       :maxNumber="1"></uploadPicture>
      </div>
    </n-modal>
  </div>
</template>

<script>
import { useStore } from 'vuex'

import { useDialog } from 'naive-ui'

import { nextTick, reactive, getCurrentInstance, onMounted, onBeforeUnmount, watchEffect, toRefs } from 'vue'
import imgUrl from '../../../static/tou.png'
import imgUrl2 from '../../../static/tou2.jpg'
import { ElMessage } from 'element-plus'

import emoji from './emoji'
import uploadPicture from './uploadPicture'

export default {
  components: {
    uploadPicture,
    emoji
  },
  props: {
    currentChatFriendId: {
      type: Number
    },
    currentChatGroupId: {
      type: Number
    },
    friends: {
      type: Object
    },
    groups: {
      type: Object
    },
    imMessages: {
      type: Object
    },
    groupMessages: {
      type: Object
    },
    imageList: {
      type: Array
    }
  },
  setup (props, context) {
    const globalProperties = getCurrentInstance().appContext.config.globalProperties
    const $common = globalProperties.$common
    const $http = globalProperties.$http
    const $constant = globalProperties.$constant
    const store = useStore()
    const dialog = useDialog()

    const data = reactive({
      // 发送消息
      msg: '',

      // 聊天图片
      showPictureDialog: false,
      picturePrefix: '',
      showPopoverImage: false
    })

    function sendPicture () {
      if ($common.isEmpty(store.state.currentUser.email)) {
        ElMessage({
          message: '请先绑定邮箱！',
          type: 'error'
        })
        return
      }

      if (!$common.isEmpty(props.currentChatFriendId)) {
        data.picturePrefix = 'im/friendMessage'
        data.showPictureDialog = true
      } else if (!$common.isEmpty(props.currentChatGroupId)) {
        data.picturePrefix = 'im/groupMessage'
        data.showPictureDialog = true
      }
    }

    function addPicture (res) {
      data.msg += '<' + store.state.currentUser.username + ',' + res + '>'
      data.showPictureDialog = false
    }

    function openFriendCircle (userId, avatar, username) {
      context.emit('openFriendCircle', userId, avatar, username)
    }

    function addEmoji (key) {
      data.msg += key
    }

    function sendImage (url) {
      data.msg += '<' + store.state.currentUser.username + ',' + url + '>'
      data.showPopoverImage = false
      doSend()
    }

    function sendPoetry (type) {
      if (type === 1) {
        sendGuShi()
      } else if (type === 2) {
        sendYiyan()
      } else if (type === 3) {
        sendDog()
      } else if (type === 4) {
        sendJitang()
      } else if (type === 5) {
        sendShehui()
      }
    }

    function sendGuShi () {
      const xhr = new XMLHttpRequest()
      xhr.open('get', $constant.jinrishici)
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          const guShi = JSON.parse(xhr.responseText).content
          if (!$common.isEmpty(guShi)) {
            data.msg = guShi
            doSend()
          }
        }
      }
      xhr.send()
    }

    function sendYiyan () {
      const xhr = new XMLHttpRequest()
      xhr.open('get', $constant.yiyan)
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          const yiyan = xhr.responseText
          if (!$common.isEmpty(yiyan)) {
            data.msg = yiyan.substring(1, yiyan.length - 1)
            doSend()
          }
        }
      }
      xhr.send()
    }

    function sendDog () {
      const xhr = new XMLHttpRequest()
      xhr.open('get', $constant.dog)
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          const dog = xhr.responseText
          if (!$common.isEmpty(dog)) {
            data.msg = dog.substring(1, dog.length - 1)
            doSend()
          }
        }
      }
      xhr.send()
    }

    function sendJitang () {
      const xhr = new XMLHttpRequest()
      xhr.open('get', $constant.jitang)
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          const jitang = xhr.responseText
          if (!$common.isEmpty(jitang)) {
            data.msg = jitang.substring(1, jitang.length - 1)
            doSend()
          }
        }
      }
      xhr.send()
    }

    function sendShehui () {
      const xhr = new XMLHttpRequest()
      xhr.open('get', $constant.shehui)
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          const shehui = xhr.responseText
          if (!$common.isEmpty(shehui)) {
            data.msg = shehui.substring(1, shehui.length - 1)
            doSend()
          }
        }
      }
      xhr.send()
    }

    function send (e) {
      if (e && (e.ctrlKey || e.shiftKey) && e.keyCode === 13) {
        e.returnValue = false
        data.msg = data.msg + '\n'
      } else if (e && e.keyCode === 13) {
        e.returnValue = false
        doSend()
      }
    }

    function doSend () {
      if ($common.isEmpty(data.msg)) {
        return
      }

      if (!$common.isEmpty(props.currentChatFriendId)) {
        const message = {
          messageType: 1,
          content: data.msg,
          fromId: store.state.currentUser.id,
          toId: props.currentChatFriendId,
          avatar: store.state.currentUser.avatar
        }
        let success = false
        context.emit('sendMsg', JSON.stringify(message), val => {
          success = val
        })
        if (success) {
          data.msg = ''
        }
      } else if (!$common.isEmpty(props.currentChatGroupId)) {
        const message = {
          messageType: 2,
          content: data.msg,
          fromId: store.state.currentUser.id,
          groupId: props.currentChatGroupId,
          avatar: store.state.currentUser.avatar,
          username: store.state.currentUser.username
        }
        let success = false
        context.emit('sendMsg', JSON.stringify(message), val => {
          success = val
        })
        if (success) {
          data.msg = ''
        }
      }
    }

    return {
      imgUrl,
      imgUrl2,
      ...toRefs(data),
      openFriendCircle,
      addEmoji,
      addPicture,
      sendPicture,
      sendImage,
      sendPoetry,
      send,
      doSend
    }
  }
}
</script>

<style scoped>
.msg-container {
  background: var(--midWhite);
  overflow-y: scroll;
  height: calc(100% - 240px);
}

.msg-one {
  margin: 15px 20px;
  display: flex;
  align-items: flex-start;
}

.message {
  max-width: 50%;
  padding: 5px 10px;
  line-height: 25px;
  word-break: break-all;
  position: relative;
  color: var(--black);
  margin: 0 12px 0 12px;
}

.message::before {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border: 3px solid;
  top: 0;
}

.message-left .message {
  background-color: var(--white);
  border-radius: 0 4px 4px 4px;
}

.message-left .message::before {
  left: -6px;
  border-color: var(--white) var(--white) transparent transparent;
}

.message-right {
  flex-direction: row-reverse;
}

.message-right .message {
  background-color: var(--messageColor);
  border-radius: 4px 0 4px 4px;
}

.message-right .message::before {
  right: -6px;
  border-color: var(--messageColor) transparent transparent var(--messageColor);
}

.msg-date, .msg-user {
  font-size: 12px;
  color: var(--greyFont);
}

.myEmoji {
  transition: all 0.5s;
  margin-right: 15px;
  cursor: pointer;
}

.myEmoji:hover {
  transform: scale(1.2);
}

.message-content {
  width: calc(100% - 30px);
  margin: 0 15px;
  box-sizing: border-box;
  height: calc(100% - 100px);
  display: block;
  border: none;
  outline: none;
  box-shadow: none;
  resize: none;
  font-size: 18px;
}

.message-send {
  float: right;
  padding: 10px 30px 15px;
}

.message-send .n-button {
  height: 30px;
  padding: 10px 25px;
}

.image-list {
  overflow: auto;
  max-width: 400px;
  max-height: 200px;
  display: flex;
  flex-flow: wrap;
  gap: 10px;
}

@media screen and (max-width: 400px) {
  .msg-one {
    margin: 15px 10px;
  }

  .image-list {
    max-width: 230px !important;
  }
}
</style>
